﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using SD.IBUS;
using SD.Entities;
using SD.BUS;
using System.Collections.Generic;

namespace SD.UI
{
    public partial class UpdateTeam : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Set value for Session
                Session["departId"] = Request.Params["departId"];
                //If departId have a valid, this is amend page else create page
                if (Request.Params["teamId"] == null)
                {
                    btnInActive.Visible = false;
                }
                else
                {
                    LoadData();
                    // set active status
                    ITeamBIZ teamBIZ = new TeamBIZ();
                    teamBIZ.SetActive(Request.Params["teamId"], true);
                    
                }
            }
        }
        protected void LoadData()
        {
            ITeamBIZ teamBIZ = new TeamBIZ();
            Team team = null;

            team = teamBIZ.GetById(Request.Params["teamId"]);

            if (team == null) // error occur
            {
                return;
            }

            // Set value for detail 1 tab
            tbxDirectorateName.Text = team.Name;

            tbxDirShortDes.Text = team.ShortDescription;

            tbxLeadContact.Text = team.Contact == null ? "N/A" : team.Contact.Surname;

            if (team.Address != null) // set address if it is not null
            {
                // set address details
                tbxAddressLine1.Text = team.Address.Line1;
                tbxAddressLine2.Text = team.Address.Line2;
                tbxAddressLine3.Text = team.Address.Line3;

                tbxCityTown.Text = team.Address.Town == null ? "" : team.Address.Town.Name;
                tbxCounty.Text = team.Address.County == null ? "" : team.Address.County.Name;
                tbxNationCountry.Text = team.Address.Country == null ? "" : team.Address.Country.Name;
                tbxPostcode.Text = team.Address.PostCode;
            }

            tbxDirFullDescription.Text = team.FullDescription;

            tbxSICCode.Text = team.BusinessType == null ? "N/A" : team.BusinessType.RefCode;

            tbxTypeOfBussiness.Text = team.BusinessType == null ? "N/A" : team.BusinessType.RefValue;

            //tbxOrgShortDes.Text = directorate.ShortDescription;

            tbxPhoneNumber.Text = team.Phone;

            tbxWebAddress.Text = team.Web;

            tbxFax.Text = team.Fax;

            tbxEmail.Text = team.Email;
            // set hidden field
            txtAddressID.Value = team.Address == null ? null : team.Address.AddressId;
            txtBussinessID.Value = team.BusinessType == null ? null : team.BusinessType.RefId;
            txtContactID.Value = team.Contact == null ? null : team.Contact.ContactId;
            hdfLine1.Value = tbxAddressLine1.Text;
            hdfLine2.Value = tbxAddressLine2.Text;
            hdfLine3.Value = tbxAddressLine3.Text;
            hdfPostCode.Value = tbxPostcode.Text;
            hdfTown.Value = tbxCityTown.Text;
            hdfCountry.Value = tbxCounty.Text;
            hdfCountry.Value = tbxNationCountry.Text;
            hdfBussiness.Value = tbxTypeOfBussiness.Text;
            hdfSicCode.Value = tbxSICCode.Text;
            hdfContactName.Value = tbxLeadContact.Text;
            //set session for button back
            Session["departId"] = team.Department.DepartmentId;
        }
        /// <summary>
        /// Active tabcontainer Default
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void TabContainer1_ActiveTabChanged(object sender, EventArgs e)
        {
            Session["indexTab"] = TabContainer1.ActiveTabIndex;
        }
        protected void btnInActive_Click(object sender, EventArgs e)
        {
            ITeamBIZ iTeamBIZ = new TeamBIZ();
            iTeamBIZ.SetActive(Request.QueryString["teamId"].ToString(), false);
            ShowMessageAndRedirect(INFO_SAVE_SUCCESSFUL, "UpdateDepartment.aspx?departId=" + Session["departId"]);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Request.Params["departId"] == null)
            {
                TeamUpdate();
            }
            else
            {
                InsertTeam();
            }

        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("UpdateDepartment.aspx?departId=" + Session["departId"]);
        }

        protected void linkLookup_Click(object sender, EventArgs e)
        {
            // Load values from hidden field
            tbxAddressLine1.Text = hdfLine1.Value;
            tbxAddressLine2.Text = hdfLine2.Value;
            tbxAddressLine3.Text = hdfLine3.Value;
            tbxPostcode.Text = hdfPostCode.Value;
            tbxCityTown.Text = hdfTown.Value;
            tbxCounty.Text = hdfCountry.Value;
            tbxNationCountry.Text = hdfCountry.Value;
            tbxTypeOfBussiness.Text = hdfBussiness.Value;
            tbxSICCode.Text = hdfSicCode.Value;
            tbxLeadContact.Text = hdfContactName.Value;
        }

        protected void linkPostcode_Click(object sender, EventArgs e)
        {
            // Load values from hidden field
            tbxAddressLine1.Text = hdfLine1.Value;
            tbxAddressLine2.Text = hdfLine2.Value;
            tbxAddressLine3.Text = hdfLine3.Value;
            tbxPostcode.Text = hdfPostCode.Value;
            tbxCityTown.Text = hdfTown.Value;
            tbxCounty.Text = hdfCountry.Value;
            tbxNationCountry.Text = hdfCountry.Value;
            tbxTypeOfBussiness.Text = hdfBussiness.Value;
            tbxSICCode.Text = hdfSicCode.Value;
            tbxLeadContact.Text = hdfContactName.Value;
        }

        protected void linkTypeOfBussiness_Click(object sender, EventArgs e)
        {
            // Load values from hidden field
            tbxAddressLine1.Text = hdfLine1.Value;
            tbxAddressLine2.Text = hdfLine2.Value;
            tbxAddressLine3.Text = hdfLine3.Value;
            tbxPostcode.Text = hdfPostCode.Value;
            tbxCityTown.Text = hdfTown.Value;
            tbxCounty.Text = hdfCountry.Value;
            tbxNationCountry.Text = hdfCountry.Value;
            tbxTypeOfBussiness.Text = hdfBussiness.Value;
            tbxSICCode.Text = hdfSicCode.Value;
            tbxLeadContact.Text = hdfContactName.Value;
        }

        protected void rbtOrganization_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtOrganization.Checked)
            {
                CoppyOrganization();
                linkPostcode.Visible = false;
            }
            else
            {
                linkPostcode.Visible = true;
                tbxAddressLine1.Text = "";
                tbxAddressLine2.Text = "";
                tbxAddressLine3.Text = "";

                tbxCityTown.Text = "";
                tbxCounty.Text = "";
                tbxNationCountry.Text = "";
                tbxPostcode.Text = "";
            }
        }

        protected void rbtParent_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtParent.Checked)
            {
                CoppyParent();
                linkPostcode.Visible = false;
            }
            else
            {
                linkPostcode.Visible = true;
                tbxAddressLine1.Text = "";
                tbxAddressLine2.Text = "";
                tbxAddressLine3.Text = "";
                tbxCityTown.Text = "";
                tbxCounty.Text = "";
                tbxNationCountry.Text = "";
                tbxPostcode.Text = "";
            }
        }
        /// <summary>
        /// Coppy Address from parent
        /// </summary>
        protected void CoppyParent()
        {
            IDepartmentBIZ departBIZ = new DepartmentBIZ();
            Department depart = departBIZ.GetById(Session["departId"].ToString());
            if (depart == null)
            {
                return;
            }
            else
            {
                // set address details
                tbxAddressLine1.Text = depart.Address.Line1;
                tbxAddressLine2.Text = depart.Address.Line2;
                tbxAddressLine3.Text = depart.Address.Line3;

                tbxCityTown.Text = depart.Address.Town == null ? "" : depart.Address.Town.Name;
                tbxCounty.Text = depart.Address.County == null ? "" : depart.Address.County.Name;
                tbxNationCountry.Text = depart.Address.Country == null ? "" : depart.Address.Country.Name;
                tbxPostcode.Text = depart.Address.PostCode;

                //set hidden field
                txtAddressID.Value = depart.Address.AddressId;
            }
        }
        /// <summary>
        /// Coppy Address from Organization
        /// </summary>
        protected void CoppyOrganization()
        {
            IDepartmentBIZ idepart = new DepartmentBIZ();
            Department department = idepart.GetById(Session["departId"].ToString());
            string dirId = department.Directorate.DirectorateId;
            IDirectorateBIZ iDirBIZ = new DirectorateBIZ();
            Directorate direct = iDirBIZ.GetById(dirId);
            string orgId = direct.Organization.OrgId;
            IOrganizationBIZ iOrganizationBIZ = new OrganizationBIZ();
            Organization organization = null;
            organization = iOrganizationBIZ.GetById(orgId);
            if (organization == null) // error occur
            {
                return;
            }

            if (organization.Address != null) // set address if it is not null
            {
                // set address details
                tbxAddressLine1.Text = organization.Address.Line1;
                tbxAddressLine2.Text = organization.Address.Line2;
                tbxAddressLine3.Text = organization.Address.Line3;

                tbxCityTown.Text = organization.Address.Town == null ? "" : organization.Address.Town.Name;
                tbxCounty.Text = organization.Address.County == null ? "" : organization.Address.County.Name;
                tbxNationCountry.Text = organization.Address.Country == null ? "" : organization.Address.Country.Name;
                tbxPostcode.Text = organization.Address.PostCode;

                //set hidden field
                txtAddressID.Value = organization.Address.AddressId;
            }
        }
        protected void TeamUpdate()
        {
            ITeamBIZ iteamBIZ = new TeamBIZ();

            // Check Directorate name has existed in database
            if (IsDuplicateName(tbxDirectorateName.Text.Trim()))
            {
                ShowMessage(ERROR_DUPLICATE_NAME);

                // Load values from hidden field
                tbxAddressLine1.Text = hdfLine1.Value;
                tbxAddressLine2.Text = hdfLine2.Value;
                tbxAddressLine3.Text = hdfLine3.Value;
                tbxPostcode.Text = hdfPostCode.Value;
                tbxCityTown.Text = hdfTown.Value;
                tbxCounty.Text = hdfCountry.Value;
                tbxNationCountry.Text = hdfCountry.Value;
                tbxTypeOfBussiness.Text = hdfBussiness.Value;
                tbxSICCode.Text = hdfSicCode.Value;
                tbxLeadContact.Text = hdfContactName.Value;
            }
            else
            {
                Team team = new Team();
                // Set Detail 1
                team.TeamId = Request.QueryString["teamId"].ToString();
                team.Name = tbxDirectorateName.Text;
                team.ShortDescription = tbxDirShortDes.Text;
                team.FullDescription = tbxDirFullDescription.Text;
                team.Phone = tbxPhoneNumber.Text;
                team.Fax = tbxFax.Text;
                team.Email = tbxEmail.Text;
                team.Web = tbxWebAddress.Text;
                Address address = new Address();
                address.AddressId = String.IsNullOrEmpty(txtAddressID.Value) ? null : txtAddressID.Value;
                team.Address = address;

                ReferenceData referenceData = new ReferenceData();
                referenceData.RefId = String.IsNullOrEmpty(txtBussinessID.Value) ? null : txtBussinessID.Value;
                team.BusinessType = referenceData;

                Contact contact = new Contact();
                contact.ContactId = String.IsNullOrEmpty(txtContactID.Value) ? null : txtContactID.Value;
                team.Contact = contact;

                team.IsActive = true;

                // Update to database
                iteamBIZ.Update(team);
                ShowMessageAndRedirect(INFO_SAVE_SUCCESSFUL, "UpdateDepartment.aspx?departId=" + Session["departId"]);
            }
        }
        /// <summary>
        /// Check Duplicate Name of Directorate
        /// </summary>
        /// <param name="dirName"></param>
        /// <returns></returns>
        private Boolean IsDuplicateName(String dirName)
        {
            ITeamBIZ iTeamBIZ = new TeamBIZ();
            List<Team> lstTeam = new List<Team>();

            lstTeam = iTeamBIZ.GetDirByName(tbxDirectorateName.Text.Trim());

            if ((lstTeam.Count > 0))
            {
                if (lstTeam[0].TeamId.Equals(Request.Params["teamId"]))
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// Insert a Team
        /// </summary>
        protected void InsertTeam()
        {
            // Create IDepartmentBIZ object
            ITeamBIZ teamBIZ = new TeamBIZ();
            // Create Directorate object
            Team team = new Team();

            // Detail 1
            team.Name = tbxDirectorateName.Text;

            // Create the list of Directorate
            List<Team> listTeam = new List<Team>();

            // Check the duplication of Directorate name
            listTeam = teamBIZ.GetDirByName(team.Name.ToString().Trim());

            // Check Organization name has existed in database
            if (listTeam.Count > 0)
            {
                ShowMessage("Team name has existed in system. Please input another name.");

                // Load values to enable textbox
                tbxAddressLine1.Text = hdfLine1.Value;
                tbxAddressLine2.Text = hdfLine2.Value;
                tbxAddressLine3.Text = hdfLine3.Value;
                tbxPostcode.Text = hdfPostCode.Value;
                tbxCityTown.Text = hdfTown.Value;
                tbxCounty.Text = hdfCountry.Value;
                tbxNationCountry.Text = hdfCountry.Value;
                tbxTypeOfBussiness.Text = hdfBussiness.Value;
                tbxSICCode.Text = hdfSicCode.Value;
                tbxLeadContact.Text = hdfContactName.Value;
            }
            else
            {

                team.ShortDescription = tbxDirShortDes.Text;
                team.FullDescription = tbxDirFullDescription.Text;
                team.Phone = tbxPhoneNumber.Text;
                team.Fax = tbxFax.Text;
                team.Email = tbxEmail.Text;
                team.Web = tbxWebAddress.Text;
                // Create Address object
                Address address = new Address();
                // Bind value to object
                address.AddressId = txtAddressID.Value;
                team.Address = address;

                // Create ReferenceData object
                ReferenceData referenceData = new ReferenceData();
                // Bind value to object
                referenceData.RefId = txtBussinessID.Value;
                team.BusinessType = referenceData;

                // Create Contact object
                Contact contact = new Contact();
                // Bind value to object
                contact.ContactId = txtContactID.Value;
                team.Contact = contact;
                //create Organization object
                Department department = new Department();
                //Bind value to object
                string departId = Request.QueryString["departId"];
                department.DepartmentId = departId;
                team.Department = department;
                team.IsActive = true;
                // Insert new Directorate
                teamBIZ.Insert(team);

                // If insert successful
                ShowMessageAndRedirect(INFO_INSERT_SUCCESSFUL, "UpdateDepartment.aspx?departId=" + Request.Params["departId"]);
            }
        }
    }
}
